package at.jku.ase.communication.parsers;

import at.jku.ase.communication.SessionObject;
import at.jku.ase.utils.CryptUtils;
import at.jku.ase.utils.ObjectUtils;

import javax.crypto.SecretKey;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

public class SecretKeyParser extends ComponentParser<SecretKey> {

    public SecretKeyParser(final SessionObject session, final XMLResponse action) {
        super(session, action);
    }

    public SecretKey processRequest(XMLStreamReader reader) throws XMLStreamException {
        if (reader.next() == XMLStreamConstants.CHARACTERS) {
            System.out.println("Parsing secret key object");
            String keyString = reader.getText();
            byte[] rawKey = ObjectUtils.toByteArray(keyString);
            SecretKey secretKey = CryptUtils.decryptSecretKey(getSession().getMyPrivateKey(), rawKey);

            if (getSession().getSecretKey() == null) {// Server side
                // save the secret key that sent from client
                getSession().setSecretKey(secretKey);
            } else if (getSession().getSecretKey().equals(secretKey)) { // client side
                System.out.println("Secure connection to server is established!");
            } else {
                throw new RuntimeException("Secret Key has been modified!");
            }
        }
        return null;
    }

}
